package com.agent.spring.websocket;

import java.io.IOException;
import java.util.Map;

import com.agent.spring.SpringConstants;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;


public class SpringWebSocketHandler extends TextWebSocketHandler {
    private static final Map<String,WebSocketSession> userMap;
    private static Logger logger = Logger.getLogger(SpringWebSocketHandler.class);
    static {
        userMap = new HashedMap();
    }


    /**
     * 连接成功时候，会触发页面上onopen方法
     */
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        userMap.put(session.getAttributes().get(SpringConstants.WEBSOCKET_ID).toString(),session);
    }

    /**
     * 关闭连接时触发
     */
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        logger.info("websocket connection closed......");
        String username= (String) session.getAttributes().get(SpringConstants.WEBSOCKET_ID);
        userMap.remove(session.getAttributes().get(SpringConstants.WEBSOCKET_ID));
    }

    /**
     * js调用websocket.send时候，会调用该方法
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
    }

    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if(session.isOpen()){session.close();}
        logger.info("websocket connection closed......");
        userMap.remove(session.getAttributes().get(SpringConstants.WEBSOCKET_ID));
    }

    public boolean supportsPartialMessages() {
        return false;
    }


    /**
     * 给某个用户发送消息
     *
     * @param userName
     * @param message
     */
    public void sendMessageToUser(String userName, TextMessage message) {
        try {
            userMap.get(userName).sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public void sendMessageToUsers(TextMessage message) {
        for (String key : userMap.keySet()) {
            try {
                if (userMap.get(key).isOpen()) {
                    userMap.get(key).sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 根据name给在线用户发送消息
     *
     * @param message
     * @param names
     */
    public void sendMessageToUsersByName(String names,TextMessage message) {
        for (String key : userMap.keySet()) {
            String userName = key.split(":")[0];
            try {
                if (names.indexOf(userName) >= 0 && userMap.get(key).isOpen()) {
                    userMap.get(key).sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}